package com.tdam2013.grupo07.fragments;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;

import android.app.Activity;
import android.app.ListFragment;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.ContentResolver;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Loader;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.tdam2013.grupo07.R;

public class FragmentTabHistorialLlamadas extends ListFragment implements LoaderCallbacks<Cursor>
{
	private final int CALLS_LOADER_ID=0;
	private LlamadasAdapter llamadasAdapter;
	private final int CALL_LOG_NUMBER=1;
	private final int CALL_LOG_DATE=2;
	private final int CALL_LOG_TYPE=3;
	private final int CALL_LOG_CACHED_NAME=4;
	private final String INTENT_EXTRA_CONTACT_ID_KEY="contactId";
	private final String INTENT_EXTRA_CONTACT_NAME_KEY="contactName";

	
	private final String[] callLogQueryProjection={CallLog.Calls._ID, CallLog.Calls.NUMBER, CallLog.Calls.DATE, CallLog.Calls.TYPE ,CallLog.Calls.CACHED_NAME};
	
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
	{
            return inflater.inflate(R.layout.fragmenttab_historial, container,
                            false);
    }

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
	    super.onViewCreated(view, savedInstanceState);
	    registerForContextMenu(getListView());
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
            super.onCreate(savedInstanceState);
            Activity activity=getActivity();
            String contactName=activity.getIntent().getStringExtra(INTENT_EXTRA_CONTACT_NAME_KEY);
            if(contactName!=null)
            {
            	activity.getActionBar().setTitle(String.format("%s %s", getResources().getString(R.string.title_activity_historial), contactName));
            }
            else
            {
            	activity.getActionBar().setTitle(R.string.title_activity_historial);
            }
            llamadasAdapter=new LlamadasAdapter(getActivity(), null);
            setListAdapter(llamadasAdapter);
    		getLoaderManager().initLoader(CALLS_LOADER_ID, null, this);
    }
    
    @Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
	{
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.setHeaderTitle(getResources().getString(R.string.historial_menu_contextual_mensajes_titulo));
		menu.add(0, v.getId(), 0, getResources().getString(R.string.historial_menu_contextual_accion_eliminar));
	}
    
    @Override
	public boolean onContextItemSelected(MenuItem item)
	{
		if (item.getTitle() == getResources().getString(R.string.historial_menu_contextual_accion_eliminar))
		{
			AdapterContextMenuInfo menuInfoAdapter = (AdapterContextMenuInfo) item.getMenuInfo();
			ContentResolver cr=getActivity().getContentResolver();
			cr.delete(CallLog.Calls.CONTENT_URI, CallLog.Calls._ID+" = ?", new String[]{String.valueOf(menuInfoAdapter.id)});
			refresh();
			Toast.makeText(getActivity(),getResources().getString(R.string.historial_registro_eliminado), Toast.LENGTH_SHORT).show();
			return true;
		}
		return false;
	}
    
    public void refresh()
    {
		  getLoaderManager().restartLoader(CALLS_LOADER_ID,null, this);
    }

	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle args)
	{
		SharedPreferences preferences= PreferenceManager.getDefaultSharedPreferences(getActivity());
		String callsOrder=preferences.getString(getResources().getString(R.string.lista_ordenamiento_historial_cronologico), getResources().getString(R.string.ajustes_ordenamiento_opciones_desc));
		String selection="";
		LinkedList<String> selectionArgs=new LinkedList<String>();
		if(preferences.getBoolean(getResources().getString(R.string.activity_ajustes_filtrar_historial_llamadas_opcion_recibidas_key), true))
		{
			selection= String.format(" ( %s = ?", CallLog.Calls.TYPE);
			selectionArgs.add(String.valueOf(CallLog.Calls.INCOMING_TYPE));
		}
		if(preferences.getBoolean(getResources().getString(R.string.activity_ajustes_filtrar_historial_llamadas_opcion_realizadas_key), true))
		{
			selection+=selectionArgs.size()!=0?selection= String.format(" OR %s = ?", CallLog.Calls.TYPE): String.format(" ( %s = ?", CallLog.Calls.TYPE);
			selectionArgs.add(String.valueOf(CallLog.Calls.OUTGOING_TYPE));
		}
		if(preferences.getBoolean(getResources().getString(R.string.activity_ajustes_filtrar_historial_llamadas_opcion_perdidas_key), true))
		{
			selection+=selectionArgs.size()!=0?selection= String.format(" OR %s = ?", CallLog.Calls.TYPE): String.format(" ( %s = ?", CallLog.Calls.TYPE);
			selectionArgs.add(String.valueOf(CallLog.Calls.MISSED_TYPE));
		}
		
		long contactId=getActivity().getIntent().getLongExtra(INTENT_EXTRA_CONTACT_ID_KEY, -1);
		if(contactId!=-1)
		{
			String[] telephoneNumbers=getContactsTelephoneNumbers(contactId);
			if(telephoneNumbers.length>0)
			{
				selection+=selection.length()>0?" ) AND (":"(";
				for(int i=0; i<telephoneNumbers.length; i++)
				{
					selection+=i==0?String.format("%s = ?", CallLog.Calls.NUMBER) : String.format(" OR %s = ?", CallLog.Calls.NUMBER);
					selectionArgs.add(telephoneNumbers[i]);
				}
			}
			else
			{
					return null;
			}
		}
		selection+=selection.length()>0?" ) ":"";
		return new CursorLoader(getActivity(), CallLog.Calls.CONTENT_URI, callLogQueryProjection, selection, selectionArgs.toArray(new String[selectionArgs.size()]), String.format("%s %s", CallLog.Calls.DATE , callsOrder));
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
		llamadasAdapter.swapCursor(data);
	}

	@Override
	public void onLoaderReset(Loader<Cursor> loader) {
		llamadasAdapter.swapCursor(null);		
	}
	
	private String[] getContactsTelephoneNumbers(long contactId)
	{
		LinkedList<String> telephoneNumbers=new LinkedList<String>();
		Cursor pCur = getActivity().getContentResolver().query(
				ContactsContract.CommonDataKinds.Phone.CONTENT_URI,new String[]{ContactsContract.CommonDataKinds.Phone.CONTACT_ID, ContactsContract.CommonDataKinds.Phone.NUMBER},
				ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
				new String[] { String.valueOf(contactId) }, null);
		while (pCur.moveToNext()) {
			telephoneNumbers.add(pCur.getString(1));
		}
		pCur.close();
		return telephoneNumbers.toArray(new String[telephoneNumbers.size()]);
	}
	
	public class LlamadasAdapter extends CursorAdapter {
		private LayoutInflater inflater;
		
		class ItemContenedor {
			ImageView itemIcono;
			TextView itemAccionPrincipal;
			TextView itemDetalleAccion;
			TextView itemFechaAccion;
		}
		
		public LlamadasAdapter(Context context, Cursor cursor) {
			super(context, cursor, false);
			inflater=LayoutInflater.from(context);
		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			View view = inflater.inflate(R.layout.item_historial, null);
			ItemContenedor itemContenedor = new ItemContenedor();
			itemContenedor.itemIcono = (ImageView) view.findViewById(R.id.iconoAccion);
			itemContenedor.itemAccionPrincipal = (TextView) view.findViewById(R.id.accionPrincipal);
			itemContenedor.itemDetalleAccion =  (TextView) view.findViewById(R.id.detalleAccion);
			itemContenedor.itemFechaAccion =  (TextView) view.findViewById(R.id.fechaAccion);
			view.setTag(itemContenedor);
			
			String telephoneNumber=cursor.getString(CALL_LOG_NUMBER);
			String cachedName=cursor.getString(CALL_LOG_CACHED_NAME);
			
			if(cachedName!=null)
			{
				itemContenedor.itemAccionPrincipal.setText(cachedName);
				itemContenedor.itemDetalleAccion.setVisibility(View.VISIBLE);
				itemContenedor.itemDetalleAccion.setText(telephoneNumber);
			}
			else
			{
				itemContenedor.itemAccionPrincipal.setText(telephoneNumber);
				itemContenedor.itemDetalleAccion.setVisibility(View.GONE);
			}
			
			itemContenedor.itemDetalleAccion.setText(telephoneNumber);
			
			switch (cursor.getInt(CALL_LOG_TYPE)) {
			case CallLog.Calls.INCOMING_TYPE:
				itemContenedor.itemIcono.setImageResource(R.drawable.call_incoming);
				break;
			case CallLog.Calls.MISSED_TYPE:
				itemContenedor.itemIcono.setImageResource(R.drawable.call_missed);			
				break;
			case CallLog.Calls.OUTGOING_TYPE:
				itemContenedor.itemIcono.setImageResource(R.drawable.call_outgoing);				
				break;
			default:
				break;
			}
			
			Date date=new Date(cursor.getLong(CALL_LOG_DATE));
			SimpleDateFormat formatter = new SimpleDateFormat(getResources().getString(R.string.date_time_format));
			itemContenedor.itemFechaAccion.setText(formatter.format(date));
			return view;
		}
		
		@Override
		public void bindView(View view, Context context, Cursor cursor)
		{
			ItemContenedor itemContenedor =(ItemContenedor) view.getTag();
			String telephoneNumber=cursor.getString(CALL_LOG_NUMBER);
			String cachedName=cursor.getString(CALL_LOG_CACHED_NAME);
			
			if(cachedName!=null)
			{
				itemContenedor.itemAccionPrincipal.setText(cachedName);
				itemContenedor.itemDetalleAccion.setVisibility(View.VISIBLE);
				itemContenedor.itemDetalleAccion.setText(telephoneNumber);
			}
			else
			{
				itemContenedor.itemAccionPrincipal.setText(telephoneNumber);
				itemContenedor.itemDetalleAccion.setVisibility(View.GONE);
			}
			
			itemContenedor.itemDetalleAccion.setText(telephoneNumber);
			
			switch (cursor.getInt(CALL_LOG_TYPE)) {
			case CallLog.Calls.INCOMING_TYPE:
				itemContenedor.itemIcono.setImageResource(R.drawable.call_incoming);
				break;
			case CallLog.Calls.MISSED_TYPE:
				itemContenedor.itemIcono.setImageResource(R.drawable.call_missed);			
				break;
			case CallLog.Calls.OUTGOING_TYPE:
				itemContenedor.itemIcono.setImageResource(R.drawable.call_outgoing);				
				break;
			default:
				break;
			}
			
			Date date=new Date(cursor.getLong(CALL_LOG_DATE));
			SimpleDateFormat formatter = new SimpleDateFormat(getResources().getString(R.string.date_format));
			itemContenedor.itemFechaAccion.setText(formatter.format(date));
		}
	}
}
